import singleton from "../libs/singleton";
import serial from "./serial";

class runSetp1 {
	#serial;
	#config;
	//干燥压力值
	drying_pressure_number;
	lower_pressure_number;
	//测漏
	p1;
	p2;
	constructor() {
		this.#serial = new serial();
		this.#config = {
			//干燥压力值
			drying_pressure: 150,
			//真空期内胆降压和蒸发器降压
			lower_pressure: 168
		}
		this.init()

		this.#serial.watch = (canId, data) => {
			// console.log('watch', canId, data)

			if (canId == 1010) {
				if (this.drying_pressure_number >= 3) {
					// 超出次数终止
					this.err("报警E1（内胆预真空降压失败）", 1010);
					return;
				}
				if (this.#config.drying_pressure > data) {
					console.log("====重新执行", data, this.drying_pressure_number)
					this.drying_pressure_number++;
					this.checkDryPressure()
					return;
				}
				this.leakDetection()
			}
			if (canId == 1021) {
				this.p1 = data;
				console.log("测漏1", this.p1)
			}
			if (canId == 1022) {
				this.p2 = data;
				if (this.p1 - this.p2 < 30) {
					this.err("报警E3（内胆泄漏率超标）", 1022);
					return;
				}
				console.log("测漏2", this.p1, this.p2)
				this.preheat()
			}
			if (canId == 1030) {
				console.log("执行下一步2")
				this.lowerPressure()
			}
			
			if (canId == 1040) {
				if (this.lower_pressure_number >= 4) {
					// 超出次数终止
					this.err("报警E1（内胆预真空降压失败）", 1040);
					return;
				}
				if (this.#config.lower_pressure > data) {
					console.log("====重新执行", data, this.lower_pressure_number)
					this.lower_pressure_number++;
					this.lowerPressure()
					return;
				}
				console.log('执行测试灭菌舱的压力值') 
			}
		}

	}

	init() {
		//干燥压力值
		this.drying_pressure_number = 1;
		//测漏
		this.p1 = 0;
		this.p2 = 0;

		console.log("初始化数据完成")
	}

	runder() {
		this.checkDryPressure()
	}
	/**
	 * 真空期内胆降压，抽到干燥压力值
	 * 在120S内未到干燥压力值，报警E1（内胆预真空降压失败）
	 * 业务逻辑
	 * 120s后发送指令获取压力值是否到指定值。
	 *   未到指定值 跳出整个功能版块
	 * 
	 */
	checkDryPressure() {
		//发送指令检测
		setTimeout(() => {
			console.log("SETP1: 执行干燥压力值")
			this.#serial.send(1010)
		}, 4000)

	}

	/**
	 * 测漏
	 * 等待10s,记录初始压力P1，30s后记录结束压力P2,
	 * 计算压力回升Tank=|P1-P2|/30 
	 * 如果Tank>=自动干燥的泄露率（编号Ⅰ）并且，
	 * Tank<=腔体升压速率，会触发自动干燥，干燥完成后，
	 * 再次自动运行流程如果升压速率>腔体升压速率,报警E3（内胆泄漏率超标）
	 */

	leakDetection() {
		console.log("SETP2: 执行测漏")
		this.#serial.send(1020)
		//记录初始压力P1
		setTimeout(() => {
			this.#serial.send(1021)
			//30s后记录结束压力P2
			setTimeout(() => {
				this.#serial.send(1022)
			}, 30000)
		}, 10000)
	}

	//预热
	preheat() {
		console.log("SETP3: 执行预热")
		this.#serial.send(1030)
	}
	/**
	 * 真空期内胆降压和蒸发器降压
	 * 在120S内灭菌舱的压力应低于“真空期内胆降压值设定（编号D）”
	 * （否则判定为E1（内胆预真空降压失败）；
	 * 出现此故障时应检查真空动力系统及系统整体的泄漏值是否出现故障）
	 */
	lowerPressure() {
		console.log("SETP4: 执行预热")
		setTimeout(_ => {
			this.#serial.send(1040)
		}, 3000)
	}


	done() {

	}

	err(msg, key) {
		
	}

}


export default singleton(runSetp1);